package com.course.api.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.course.api.entity.Course;
import com.course.api.mapper.CourseMapper;
import com.course.api.mapper.UserMapper;
import com.course.api.service.ICourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    CourseMapper courseMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public void selectCourseById(Long courseId, Long userId) {
        // 记录选择当前课程的学生id
        Course course = courseMapper.selectById(courseId);
        String studentIds = course.getStudentIds();
        if (studentIds == null || studentIds.equals("")) {
            studentIds = userId.toString();
        } else {
            studentIds = studentIds + "," + userId.toString();
        }
        course.setSelectedNumber(course.getSelectedNumber() + 1);
        course.setTotalNumber(course.getTotalNumber() - 1);
        course.setStudentIds(studentIds);
        courseMapper.updateById(course);
    }

    @Override
    public void deselectCourseById(Long courseId, Long userId) {
        Course course = courseMapper.selectById(courseId);
        String studentIds = course.getStudentIds();
        int index = studentIds.indexOf(userId.toString());
        if (studentIds.length() == 1) {
            studentIds = "";
        } else {
            if (index == 0) {
                studentIds = studentIds.replace(userId + ",", "");
            } else if (index > 0) {
                studentIds = studentIds.replace("," + userId, "");
            }
        }
        course.setTotalNumber(course.getTotalNumber() + 1);
        course.setSelectedNumber(course.getSelectedNumber() - 1);
        course.setStudentIds(studentIds);
        courseMapper.updateById(course);
    }
}
